package com.mofeng.myshop.controller.portal;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.mofeng.myshop.domain.po.Commodity;
import com.mofeng.myshop.domain.po.CommodityCategory;
import com.mofeng.myshop.domain.po.Images;
import com.mofeng.myshop.domain.test.GoodsList;
import com.mofeng.myshop.mapper.CommodityCategoryMapper;
import com.mofeng.myshop.mapper.CommodityMapper;
import com.mofeng.myshop.mapper.GoodsListMapper;
import com.mofeng.myshop.mapper.ImagesMapper;
import com.mofeng.myshop.properties.FileProperty;
import com.mofeng.myshop.service.ImageService;
import com.mofeng.myshop.service.fileupload.FileServer;
import com.mofeng.myshop.service.fileupload.factory.FileFactory;
import com.mofeng.myshop.until.Constants;
import com.mofeng.myshop.until.MyUtil;
import com.mofeng.myshop.until.R;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RestController
@RequestMapping("/test")
public class TestController {

    private final GoodsListMapper goodsListMapper;
    private final CommodityCategoryMapper commodityCategoryMapper;
    private final CommodityMapper commodityMapper;
    private final ImageService imageService;
    private final ImagesMapper imagesMapper;
    private final FileProperty config;

    //    @PostConstruct
    public void changeImage() throws Exception {
        List<Images> imagesList = imagesMapper.findAll();
        for (Images images : imagesList) {
            String url = images.getUrl();
            String[] split = url.split("/");
            String imageUrl = split[split.length - 1];
            String[] path = imageUrl.split("_");
            String dayValue = MyUtil.DateUtil.getTimeStr(Long.parseLong(path[0]), "yyyy_MM_dd");
            String name = path[1];
            String type = name.split("\\.")[1];
            String id = name.replace(type, "").replace(".", "");
            String filePath = new StringBuffer(config.getImagePath())
                    .append(dayValue).append(File.separator)
                    .append(type).append(File.separator).append(name)
                    .toString();
            File oldfile = new File(filePath);
            if (oldfile.exists()) {
                String oldFilePath = oldfile.getAbsolutePath();
                String fileName = oldfile.getName();

                // 找到文件的扩展名
                int dotIndex = fileName.lastIndexOf('.');
                String baseName = (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex); // 不包含扩展名的文件名
                String extension = (dotIndex == -1) ? "" : fileName.substring(dotIndex); // 文件的扩展名（包括点）

                // 新文件名：加上 "-p" 后缀
                String newFileName = baseName + "-p" + extension;

                // 创建新的 File 对象
                File newFile = new File(oldfile.getParent(), newFileName);
                boolean b = oldfile.renameTo(newFile);
                if (b) {
                    System.out.println("文件重命名成功: " + newFile.getAbsolutePath());
                } else {
                    System.out.println("文件重命名失败");
                }
                String fileType = MyUtil.FileUtil.getFileType(newFile, "PNG");
                try {
                    MyUtil.ImageUtil.compressImage(newFile, oldfile, fileType, 0.05f);
                } catch (Exception e) {
                    System.out.println("错误路径： " + newFile.getAbsolutePath());
                    e.printStackTrace();
                }
            }
        }

    }

//    @GetMapping("/domain/{domain}")
//    public R getQrCodeImage(@PathVariable("domain") String domain) {
//        try {
//            InetAddress inetAddress = InetAddress.getByName(domain);
//            return R.SUCCESS(inetAddress.getHostAddress());
//        } catch (UnknownHostException e) {
//            String errMsg = domain + "，域名无法解析，报错信息: " + e.getMessage();
//            e.printStackTrace();
//            throw new RuntimeException(errMsg, e);
//        }
//    }

    //    @Operation(summary = "移植数据库")
//    @PostMapping("/")
//    @PostConstruct
//    public void changeCommand() {
//        List<Commodity> commodityList = commodityMapper.findAll();
//        List<Commodity> commodityListDel = new ArrayList<>();
//        List<Commodity> commodityListAdd = new ArrayList<>();
//        for (Commodity commodity : commodityList) {
//            Long id = commodity.getId();
//            if (id < 2000) {
//                Commodity commodityAdd = new Commodity();
//                commodityAdd.setName(commodity.getName());
//                commodityAdd.setRemarks(commodity.getRemarks());
//                commodityAdd.setDescription(commodity.getDescription());
//                commodityAdd.setOrderIndex(commodity.getOrderIndex());
//                commodityAdd.setCreateTime(commodity.getCreateTime());
//                commodityAdd.setUpdateTime(commodity.getUpdateTime());
//                commodityAdd.setDelete(commodity.getDelete());
//                commodityAdd.setImage(commodity.getImage());
//                commodityAdd.setIconImage(commodity.getIconImage());
//                commodityAdd.setCode(commodity.getCode());
//                commodityAdd.setBasePrice(commodity.getBasePrice());
//                commodityAdd.setMultiplierUp(commodity.getMultiplierUp());
//                commodityAdd.setLevelUp(commodity.getLevelUp());
//                commodityAdd.setLevelTop(commodity.getLevelTop());
//                commodityAdd.setDiscount(commodity.getDiscount());
//                commodityAdd.setCommodityCategoryId(commodity.getCommodityCategoryId());
//                commodityAdd.setProjectId(commodity.getProjectId());
//                commodityAdd.setHot(commodity.getHot());
//
//                commodityListAdd.add(commodityAdd);
//                commodityListDel.add(commodity);
//            }
//        }
//
//        for (Commodity commodity : commodityListAdd) {
//            commodityMapper.insert(commodity);
//        }
//        for (Commodity commodity : commodityListDel) {
//            commodityMapper.deleteById(commodity.getId());
//        }
//    }

    //    @Operation(summary = "移植数据库")
//    @PostMapping("/")
//    @PostConstruct
//    public void changeDatabase() {
//
//        List<GoodsList> goodsListList = goodsListMapper.findAll();
//        List<CommodityCategory> commodityCategorySet = commodityCategoryMapper.findList(null, null);
//        HashMap<String, Long> nameLongHashMap = new HashMap<>();
//        for (CommodityCategory commodityCategory : commodityCategorySet) {
//            nameLongHashMap.put(commodityCategory.getName(), commodityCategory.getId());
//        }
//
//        Map<String, List<GoodsList>> stringListMap = goodsListList.stream().collect(Collectors.groupingBy(GoodsList::getGoodstype));
//        List<Commodity> commodityList = new ArrayList<>();
//        int i = 0;
//        for (String name : stringListMap.keySet()) {
//            List<GoodsList> goodsListList1 = stringListMap.get(name);
//            for (GoodsList goodsList : goodsListList1) {
//                Long commodityCategoryId = nameLongHashMap.get(name);
//                if (commodityCategoryId == null) {
//                    System.out.println(name);
//                }
//                Commodity commodity = new Commodity();
//                commodity.setId(goodsList.getId());
//                commodity.setCommodityCategoryId(commodityCategoryId);
//                commodity.setBasePrice(MyUtil.NumberUtil.asDouble(goodsList.getGoodsPrice()));
//                commodity.setPrice(MyUtil.NumberUtil.asDouble(goodsList.getGoodsPrice()));
//                commodity.setDelete(Constants.State.DEFAULT_STATE);
//                commodity.setHot(Constants.State.DEFAULT_STATE);
//                commodity.setCode(goodsList.getGoodscode());
//                commodity.setName(goodsList.getGoodsname());
//                commodity.setImage(goodsList.getGoodsimg());
//                commodity.setLevelUp(MyUtil.NumberUtil.asDouble(goodsList.getGoodsKLPriceUP()));
//                commodity.setMultiplierUp(MyUtil.NumberUtil.asDouble(goodsList.getGoodsPrice()));
//                commodity.setDiscount(MyUtil.NumberUtil.asDouble(goodsList.getGoodsDiscount()));
//                commodity.setLevelTop(MyUtil.NumberUtil.asInt(goodsList.getDinMaxLv()));
//                commodity.setProjectId(1801975023006826497L);
//                commodity.setOrderIndex(i);
//                Date date = new Date();
//                commodity.setCreateTime(date);
//                commodity.setUpdateTime(date);
//                commodityList.add(commodity);
//                i += 5;
//            }
//        }
//        commodityList.forEach(commodity -> {
//            commodityMapper.insert(commodity);
//        });
//
//    }

    //    @Operation(summary = "移植数据库")
//    @PostMapping("/")
//    @PostConstruct
//    @Transactional(rollbackFor = Exception.class)
//    public void copyCommand() {
//        List<CommodityCategory> commodityCategorySet = commodityCategoryMapper.findList(null, null);
//        List<Commodity> commodityList = commodityMapper.findAll();
//        List<Commodity> commodityListCopy = new ArrayList<>();
//        Map<Long, List<Commodity>> commodityByCategoryId = commodityList.stream().collect(Collectors.groupingBy(Commodity::getCommodityCategoryId));
//        Date date = new Date();
//        Long projectId = 1815374777308868610L;
//        for (CommodityCategory commodityCategory : commodityCategorySet) {
//            Long oldCategoryId = commodityCategory.getId();
//            commodityCategory.setId(null);
//            commodityCategory.setProjectId(projectId);
//            commodityCategory.setCreateTime(date);
//            commodityCategory.setUpdateTime(date);
//            int insert = commodityCategoryMapper.insert(commodityCategory);
//            List<Commodity> commodityList1 = commodityByCategoryId.get(oldCategoryId);
//            commodityList1.forEach(commodity -> {
//                commodity.setId(null);
//                commodity.setCommodityCategoryId(commodityCategory.getId());
//                commodity.setProjectId(projectId);
//                commodity.setCreateTime(date);
//                commodity.setUpdateTime(date);
//                commodityListCopy.add(commodity);
//            });
//        }
//        commodityListCopy.forEach(commodity -> {
//            commodityMapper.insert(commodity);
//        });
//    }

    private final FileFactory fileFactory;

    //    @PostConstruct
    public void changeImages() {
        File directory = new File("D:\\Ark\\ARK_img");
        File[] files = directory.listFiles();
        HashMap<String, String> imageMap = new HashMap<>();
        for (File file : files) {
            String name = file.getName();
            FileToMultipartFile fileToMultipartFile = new FileToMultipartFile(file);
            R r = imageService.addImage(fileToMultipartFile);
            Object data1 = r.getData();
            if (data1 == null) {
                System.out.println("*********************************************");
                System.out.println(name);
                System.out.println("*********************************************");
            } else {
                String data = data1.toString();
                imageMap.put(name, data);
            }

        }
        List<Commodity> commodityList = commodityMapper.findAll();
        for (Commodity commodity : commodityList) {
            String image = commodity.getImage();
            commodity.setImage(imageMap.get(image));
            commodityMapper.updateById(commodity);
        }
    }

    public class FileToMultipartFile implements MultipartFile {

        private final File file;

        public FileToMultipartFile(File file) {
            this.file = file;
        }

        @Override
        public String getName() {
            return file.getName();
        }

        @Override
        public String getOriginalFilename() {
            return file.getName();
        }

        @Override
        public String getContentType() {
            try {
                return Files.probeContentType(file.toPath());
            } catch (IOException e) {
                return null;
            }
        }

        @Override
        public boolean isEmpty() {
            return file.length() == 0;
        }

        @Override
        public long getSize() {
            return file.length();
        }

        @Override
        public byte[] getBytes() throws IOException {
            return Files.readAllBytes(file.toPath());
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new FileInputStream(file);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            Files.copy(file.toPath(), dest.toPath());
        }
    }
}
